<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>添加文章</title>
  <link rel="stylesheet" href="./lib/layui/css/layui.css">
  <link rel="stylesheet" href="./node_modules/simplemde/dist/simplemde.min.css">
  <link rel="stylesheet" href="./node_modules//github-markdown-css/github-markdown.css">
  <link rel="stylesheet" href="./lib/highlight/styles/atom-one-light.css">
</head>

<body style="padding:10px 50px">
  <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>添加文章</legend>
  </fieldset>

  <form class="layui-form layui-form-pane" action="javascript:;">
    <div class="layui-form-item">
      <label class="layui-form-label">图片</label>
      <div class="layui-input-block">
        <img id="uploadImg" src="./images/upload.png" style="width:150px;height:100px">
      </div>
    </div>

    <div class="layui-form-item" pane="">
      <label class="layui-form-label">标签</label>
      <div class="layui-input-block" id="tags"></div>
    </div>

    <div class="layui-form-item">
      <label class="layui-form-label">标题</label>
      <div class="layui-input-block">
        <input id="title" type="text" name="title" required lay-verify="required" class="layui-input">
      </div>
    </div>

    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">摘要</label>
      <div class="layui-input-block">
        <textarea name="outline" id="outline" class="layui-textarea"></textarea>
      </div>
    </div>

    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">内容</label>
      <div class="layui-input-block">
        <textarea name="detail" id="detail" cols="30" rows="10"></textarea>
      </div>
    </div>

    <div class="layui-form-item">
      <button class="layui-btn" lay-submit="" lay-filter="sure">保存</button>
    </div>
  </form>

  <script src="./node_modules/jquery/dist/jquery.min.js"></script>
  <script src="./node_modules/simplemde/dist/simplemde.min.js"></script>
  <script src="./lib/layui/layui.js"></script>
  <script src="./lib/highlight/highlight.pack.js"></script>
  <script type="module">
    import util from './utils/util.js'

    layui.use(['element', 'layer', 'form', 'upload'], function () {
      const element = layui.element
      const layer = layui.layer
      const layedit = layui.layedit
      const form = layui.form
      const upload = layui.upload
      const model = parent.model
      const postsTable = parent.postsTable

      const simplemed = new SimpleMDE({ element: document.getElementById('detail') })

      $(".editor-preview-side").addClass("markdown-body")
      $('textarea').on('input', _ => $('pre code').each(function (i, e) { hljs.highlightBlock(e) }))

      let imageId = null
      let tags = []
      let id = util.getQueryString('id')

      if (id) {
        model.getPost(id).then(res => {
          imageId = res.image.id
          $('#uploadImg').attr('src', res.image.src)
          $('#title').val(res.title)
          $('#outline').val(res.outline)
          simplemed.value(res.detail)
          res.tags.forEach(tag => tags.push(tag.id))
          model.getTags().then(res => {
            res.data.forEach(value =>
              $('#tags').append(`
                <input type="checkbox" name="tags[]" value="${value.id}" title="${value.name}" lay-filter="tags" ${util.inArray(value.id, tags) ? "checked" : ""}>
              `)
            )
            addTagButton()
          })
        })
      } else {
        model.getTags().then(res => {
          res.data.forEach(value =>
            $('#tags').append(`
              <input type="checkbox" name="tags[]" value="${value.id}" title="${value.name}" lay-filter="tags">
            `)
          )
          addTagButton()
        })
      }

      upload.render({
        elem: '#uploadImg',
        url: model.baseRequestUrl + '/images',
        headers: { token: model.token.get() },
        before: obj => layer.load(),
        done: res => {
          layer.closeAll('loading')
          if (res.code != 200) return layer.msg('上传失败')
          imageId = res.data[0].id
          $('#uploadImg').attr('src', res.data[0].src)
        },
        error: _ => {
          layer.closeAll('loading');
          layer.msg('上传失败')
        }
      })

      function addTagButton() {
        $('#tags').append(`
          <input type="button" value="添加" id="addTag" class="layui-btn layui-btn-sm">
        `)
        form.render()

        $('#addTag').on('click', function () {
          layer.prompt({ title: '请输入标签名' }, (name, index) => {
            model.storeTag({ name }).then(tag => {
              $(this).before(`
                <input type="checkbox" name="tags[]" value="${tag.id}" title="${tag.name}" lay-filter="tags" checked>
              `)
              tags.push(tag.id)
              layer.close(index)
              form.render()
            })
          })
        })
      }

      form.on('checkbox(tags)', data => {
        let value = parseInt(data.value)
        util.inArray(value, tags) ? tags.splice($.inArray(value, tags), 1) : tags.push(value)
      })

      form.on('submit(sure)', res => {
        let markdown = simplemed.value()
        let html = simplemed.markdown(markdown)

        let data = {
          tags,
          image_id: imageId,
          title: res.field.title,
          outline: res.field.outline,
          detail: markdown
        }

        if (id) {
          model.updatePost(id, data).then(_ => {
            postsTable.reload({ page: { hash: 'posts', curr: parent.util.getHashPage('posts') } })
            parent.layer.close(parent.layer.getFrameIndex(window.name))
          })
        } else {
          model.storePost(data).then(_ => {
            postsTable.reload({ page: { hash: 'posts', curr: 1 } })
            parent.layer.close(parent.layer.getFrameIndex(window.name))
          })
        }
      })
    })
  </script>
</body>

</html>
